# -*- coding: UTF-8 -*- 

from django import forms
from django.template import RequestContext
from django.http import HttpResponse, HttpResponseRedirect
from django.template.loader import get_template
from django.core.paginator import Paginator
from django.core.urlresolvers import reverse
import datetime
from django.shortcuts import render_to_response
from django.utils import simplejson
from django.contrib.auth import authenticate,login,logout
from django.contrib.auth.decorators import login_required,user_passes_test
from django.db.models import Q
# app specific files

from models import *
from forms import *
from views_update import *
from views_follow import *


       
            
@login_required
def save_patient(request):
    form = newpatientForm(request.POST or None)
    if form is not None:
        print '0000'
        if form.is_valid():
            print '1111'
            name = form.cleaned_data['patient_name']
            age = form.cleaned_data['patient_age']
            birthdate=form.cleaned_data['patient_birthdate']
            company=form.cleaned_data['patient_company']
            home=form.cleaned_data['patient_home']
            tel=form.cleaned_data['patient_tel']
            card=form.cleaned_data['patient_card']
            native=form.cleaned_data['patient_native']
            inputdate=form.cleaned_data['patient_inputdate']
            number=form.cleaned_data['patient_number']
            remark=form.cleaned_data['patient_remark']
            gender=form.cleaned_data['patient_gender']
            pno=form.cleaned_data['Patient_no']
            hno=form.cleaned_data['hospitalized_no']
            nno=form.cleaned_data['nno']
            nho=form.cleaned_data['nho']
            
            nnos=nno.split('-')
            print nho
            nnhos=nho.split('-')
            if card == '':
                card = None

            print '2222'
            newpatient = patient(patient_name=name,
                              patient_age=age,
                              patient_birthdate=birthdate,
                              patient_company=company,
                              patient_home=home,
                              patient_tel=tel,
                              patient_card=card,
                              patient_native=native,
                              patient_inputdate=inputdate,
                              patient_number=number,
                              patient_remark=remark,
                              patient_gender=gender)
            
            newpatient.save()
            print '3333'
            newpatient2 = patient.objects.get(patient_number=number)
            
            
            for thisnno in nnos:
                newPatientNo = PatientNo(Patient_no=thisnno,
                                  patient=newpatient2)
                newPatientNo.save()
            
            for thisnho in nnhos:
                newhospitalized = hospitalized(hospitalized_no=thisnho,
                                        patient=newpatient2)
                newhospitalized.save()
                      
            print '44444'
            patient_session = request.session.get("patient",None)
            if patient_session is not None:
                del request.session['patient']
            
            request.session["patient"] =  newpatient
            flag = 1
            result = simplejson.dumps(flag)
            return HttpResponse(result) 

#            return HttpResponseRedirect("/sle/patient/list/") 
            
            
        
    else:
        form = newpatientForm()
    t = get_template('sle/patient_page.html')
    c = RequestContext(request,locals())
    return HttpResponse(t.render(c))

@login_required
def save_Infection(request):
    form = IncentiveForm(request.POST or None)
    if form is not None:        
        if form.is_valid():
            tInfection = form.cleaned_data['Infection'] #诱因
            tPregnancy = form.cleaned_data['Pregnancy'] #妊娠
            tDrugs = form.cleaned_data['Drugs'] #药物
            tTired = form.cleaned_data['Tired'] #劳累
            tPsychogenic = form.cleaned_data['Psychogenic'] #精神因素
            tFitment = form.cleaned_data['Fitment'] #装修
            tMenopause = form.cleaned_data['Menopause'] #绝经
            tOthers = form.cleaned_data['Others'] #其他            
           
            newInfection = Incentive(Infection = tInfection,
                                     Pregnancy = tPregnancy,
                                     Drugs =tDrugs,
                                     Tired = tTired,
                                     Psychogenic = tPsychogenic,
                                     Fitment = tFitment,
                                     Menopause = tMenopause,
                                     Others = tOthers,
                                     Patient = request.session.get("patient",None))
            
            newInfection.save()
            return HttpResponseRedirect("/sle/patient/list/")
    else:
        form = IncentiveForm()
    t = get_template('sle/patient_page.html')
    c = RequestContext(request,locals())
    return HttpResponse(t.render(c)) 


@login_required
def save_Manifestation(request):
    
    form = ManifestationForm(request.POST or None)
   
    if form is not None:
               
        if form.is_valid():
            
            tMenstruation = form.cleaned_data['Menstruation'] #月经
            tSkin = form.cleaned_data['Skin'] #皮肤
            tJoint = form.cleaned_data['Joint'] #关节
            tMuscle = form.cleaned_data['Muscle'] #肌肉
            tRespiratory = form.cleaned_data['Respiratory'] #呼吸
            tCardiovascular = form.cleaned_data['Cardiovascular'] #心血管
            tDigestive = form.cleaned_data['Digestive'] #消化系统
            tUrinary = form.cleaned_data['Urinary'] #泌尿系统 
            tNervous = form.cleaned_data['Nervous'] #神经系统        
            tInitial = form.cleaned_data['Initial'] #首发        
            tRaynaud = form.cleaned_data['Raynaud'] #雷诺 
            tHemotologic = form.cleaned_data['Hemotologic']#血液系统
            
            newManifestation = Manifestation(Menstruation = tMenstruation,
                                     Skin = tSkin,
                                     Joint =tJoint,
                                     Muscle = tMuscle,
                                     Respiratory = tRespiratory,
                                     Cardiovascular = tCardiovascular,
                                     Digestive = tDigestive,
                                     Urinary = tUrinary,
                                     Nervous = tNervous,
                                     Initial = tInitial,
                                     Raynaud = tRaynaud,
                                     Hemotologic = tHemotologic,
                                     Patient = request.session.get("patient",None))

            newManifestation.save()
            return HttpResponseRedirect("/sle/patient/list/")
    else:
        
        form = ManifestationForm()
    t = get_template('sle/patient_page.html')
    c = RequestContext(request,locals())
    
    return HttpResponse(t.render(c)) 

@login_required
def save_Course(request):
    form = CourseForm(request.POST or None)
   
    if form is not None:
               
        if form.is_valid():
            tCourse = form.cleaned_data['Course']
            
            newCourse = Course(Course=tCourse,Patient = request.session.get("patient",None))
            newCourse.save() 
            return HttpResponseRedirect("/sle/patient/list/")
    else:
        
        form = CourseForm()
    t = get_template('sle/patient_page.html')
    c = RequestContext(request,locals())
    
    return HttpResponse(t.render(c)) 

@login_required
def save_History(request):

    form = HistoryForm(request.POST or None)

    if form is not None:
              
        if form.is_valid():
            
            tPast = form.cleaned_data['Past']
            tFamily = form.cleaned_data['Family']
            tBirth = form.cleaned_data['Birth']
            tPregnancy = form.cleaned_data['Pregnancy']
            tBirthtime = form.cleaned_data['Birthtime']
            tAbortion = form.cleaned_data['Abortion']
            tLiving = form.cleaned_data['Living']
            tFs = form.cleaned_data['Fs']
            tMs = form.cleaned_data['Ms']
            
            newHistory = History(
                                 Past=tPast,
                                 Family=tFamily,
                                 Birth=tBirth,
                                 Pregnancy=tPregnancy,
                                 Birthtime=tBirthtime,
                                 Abortion=tAbortion,
                                 Living = tLiving,
                                 Fs=tFs,
                                 Ms=tMs,
                                 Patient = request.session.get("patient",None)
                                 )
            newHistory.save()

            return HttpResponseRedirect("/sle/patient/list/")
    else:

        form = HistoryForm()
    t = get_template('sle/patient_page.html')
    c = RequestContext(request,locals())

    return HttpResponse(t.render(c))

@login_required
def save_Physical(request):
    form = PhysicalForm(request.POST or None)
   
    if form is not None:
               
        if form.is_valid():
            tLung = form.cleaned_data['Lung']
            tHeart = form.cleaned_data['Heart']
            tLiver = form.cleaned_data['Liver']
            tSpleen = form.cleaned_data['Spleen']
            tHair = form.cleaned_data['Hair']
            tSkin2 = form.cleaned_data['Skin2']
            tEdema = form.cleaned_data['Edema']
            tJoint = form.cleaned_data['Joint']
            tMuscle2 = form.cleaned_data['Muscle2']
            tVasculitis = form.cleaned_data['Vasculitis']
            tLymph = form.cleaned_data['Lymph']
            tNervous2 = form.cleaned_data['Nervous2']
            
            
            
            newPhysical = Physical(
                                 Lung=tLung,
                                 Heart=tHeart,
                                 Liver=tLiver,
                                 Spleen=tSpleen,
                                 Hair=tHair,
                                 Skin2=tSkin2,
                                 Edema=tEdema,
                                 Joint=tJoint,
                                 Muscle2=tMuscle2,
                                 Vasculitis=tVasculitis,
                                 Lymph=tLymph,
                                 Nervous2=tNervous2,
                                 Patient = request.session.get("patient",None)
                                 )
            newPhysical.save()
            return HttpResponseRedirect("/sle/patient/list/")
    else:
        
        form = PhysicalForm()
    t = get_template('sle/patient_page.html')
    c = RequestContext(request,locals())
    
    return HttpResponse(t.render(c)) 

@login_required
def save_Standard(request):
    form = StandardForm(request.POST or None)
   
    if form is not None:
               
        if form.is_valid():
            toptionsRadios1 = form.cleaned_data['optionsRadios1']
            toptionsRadios2 = form.cleaned_data['optionsRadios2']
            toptionsRadios3 = form.cleaned_data['optionsRadios3']
            toptionsRadios4 = form.cleaned_data['optionsRadios4']
            toptionsRadios5 = form.cleaned_data['optionsRadios5']
            toptionsRadios6 = form.cleaned_data['optionsRadios6']
            toptionsRadios7 = form.cleaned_data['optionsRadios7']
            toptionsRadios8 = form.cleaned_data['optionsRadios8']
            toptionsRadios9 = form.cleaned_data['optionsRadios9']
            toptionsRadios10 = form.cleaned_data['optionsRadios10']
            toptionsRadios11 = form.cleaned_data['optionsRadios11']
            toptionsRadios12 = form.cleaned_data['optionsRadios12']
            toptionsRadios13 = form.cleaned_data['optionsRadios13']
            toptionsRadios14 = form.cleaned_data['optionsRadios14']
            toptionsRadios15 = form.cleaned_data['optionsRadios15']
            toptionsRadios16 = form.cleaned_data['optionsRadios16']
            toptionsRadios17 = form.cleaned_data['optionsRadios17']
            
            
            
            newStandard = Standard(
                                 optionsRadios1=toptionsRadios1,
                                 optionsRadios2=toptionsRadios2,
                                 optionsRadios3=toptionsRadios3,
                                 optionsRadios4=toptionsRadios4,
                                 optionsRadios5=toptionsRadios5,
                                 optionsRadios6=toptionsRadios6,
                                 optionsRadios7=toptionsRadios7,
                                 optionsRadios8=toptionsRadios8,
                                 optionsRadios9=toptionsRadios9,
                                 optionsRadios10=toptionsRadios10,
                                 optionsRadios11=toptionsRadios11,
                                 optionsRadios12=toptionsRadios12,
                                 optionsRadios13=toptionsRadios13,
                                 optionsRadios14=toptionsRadios14,
                                 optionsRadios15=toptionsRadios15,
                                 optionsRadios16=toptionsRadios16,
                                 optionsRadios17=toptionsRadios17,
                                 Patient = request.session.get("patient",None)
                                 )
            newStandard.save()
            return HttpResponseRedirect("/sle/patient/list/")
    else:
        
        form = StandardForm()
    t = get_template('sle/patient_page.html')
    c = RequestContext(request,locals())
    
    return HttpResponse(t.render(c)) 


@login_required
def create_patient(request):
    form = patientForm(request.POST or None)
    if form.is_valid():
        form.save()
        form = patientForm()

    t = get_template('sle/create_patient.html')
    c = RequestContext(request,locals())
    return HttpResponse(t.render(c))


@login_required
def list_patient(request):
  
    list_items = patient.objects.all().order_by('-id')
    paginator = Paginator(list_items ,10)


    try:
        page = int(request.GET.get('page', '1'))
    except ValueError:
        page = 1

    try:
        list_items = paginator.page(page)
    except :
        list_items = paginator.page(paginator.num_pages)

    t = get_template('sle/list_patient.html')
    c = RequestContext(request,locals())
    return HttpResponse(t.render(c))


@login_required
def view_patient(request, id):
    patient_instance = patient.objects.get(id = id)

    t=get_template('sle/view_patient.html')
    c=RequestContext(request,locals())
    return HttpResponse(t.render(c))

@login_required
def edit_patient(request, id):

    patient_instance = patient.objects.get(id=id)

    form = patientForm(request.POST or None, instance = patient_instance)

    if form.is_valid():
        form.save()

    t=get_template('sle/edit_patient.html')
    c=RequestContext(request,locals())
    return HttpResponse(t.render(c))

@login_required
def del_patient(request,id):
    
    PatientNo.objects.filter(patient_id=id).delete()
    hospitalized.objects.filter(patient_id=id).delete()
    patient.objects.get(id=id).delete()
    
    list_items = patient.objects.all()
    paginator = Paginator(list_items ,10)


    try:
        page = int(request.GET.get('page', '1'))
    except ValueError:
        page = 1

    try:
        list_items = paginator.page(page)
    except :
        list_items = paginator.page(paginator.num_pages)


    return HttpResponseRedirect("/sle/patient/list/")
    
    

@login_required
def create_patientno(request):
    form = PatientNoForm(request.POST or None)
    if form.is_valid():
        form.save()
        form = PatientNoForm()

    t = get_template('sle/create_patientno.html')
    c = RequestContext(request,locals())
    return HttpResponse(t.render(c))


@login_required
def list_patientno(request):
  
    list_items = PatientNo.objects.all()
    paginator = Paginator(list_items ,10)
    print 


    try:
        page = int(request.GET.get('page', '1'))
    except ValueError:
        page = 1

    try:
        list_items = paginator.page(page)
    except :
        list_items = paginator.page(paginator.num_pages)

    t = get_template('sle/list_patientno.html')
    c = RequestContext(request,locals())
    return HttpResponse(t.render(c))


@login_required
def view_patientno(request, id):
    patientno_instance = PatientNo.objects.get(id = id)

    t=get_template('sle/view_patientno.html')
    c=RequestContext(request,locals())
    return HttpResponse(t.render(c))

@login_required
def edit_patientno(request, id):

    patientno_instance = PatientNo.objects.get(id=id)

    form = PatientNoForm(request.POST or None, instance = patientno_instance)

    if form.is_valid():
        form.save()

    t=get_template('sle/edit_patientno.html')
    c=RequestContext(request,locals())
    return HttpResponse(t.render(c))

@login_required
def create_hospitalized(request):
    form = hospitalizedForm(request.POST or None)
    if form.is_valid():
        form.save()
        form = hospitalizedForm()

    t = get_template('sle/create_hospitalized.html')
    c = RequestContext(request,locals())
    return HttpResponse(t.render(c))


@login_required
def list_hospitalized(request):
  
    list_items = hospitalized.objects.all()
    paginator = Paginator(list_items ,10)


    try:
        page = int(request.GET.get('page', '1'))
    except ValueError:
        page = 1

    try:
        list_items = paginator.page(page)
    except :
        list_items = paginator.page(paginator.num_pages)

    t = get_template('sle/list_hospitalized.html')
    c = RequestContext(request,locals())
    return HttpResponse(t.render(c))


@login_required
def view_hospitalized(request, id):
    hospitalized_instance = hospitalized.objects.get(id = id)

    t=get_template('sle/view_hospitalized.html')
    c=RequestContext(request,locals())
    return HttpResponse(t.render(c))

def edit_hospitalized(request, id):

    hospitalized_instance = hospitalized.objects.get(id=id)

    form = hospitalizedForm(request.POST or None, instance = hospitalized_instance)

    if form.is_valid():
        form.save()

    t=get_template('sle/edit_hospitalized.html')
    c=RequestContext(request,locals())
    return HttpResponse(t.render(c))


@login_required
def check_record(request):
    flag = 0
    thispatient = patient.objects.filter(patient_number = request.GET.get('patient_number'))
    if thispatient.count() > 0:
        flag = 1
        result = simplejson.dumps(flag)
        return HttpResponse(result)
    else:
        result = simplejson.dumps(flag)
        return HttpResponse(result)

@login_required
def viewedit_patient(request,id):
    patient_instance = patient.objects.get(id = id)
    patientno_instance = PatientNo.objects.filter(patient=patient_instance)
    hospitalized_instance = hospitalized.objects.filter(patient=patient_instance)
    Incentive_instance = Incentive.objects.filter(Patient=patient_instance)
    Manifestation_instance = Manifestation.objects.filter(Patient=patient_instance)
    Course_instance = Course.objects.filter(Patient=patient_instance)
    History_instance = History.objects.filter(Patient=patient_instance)
    Physical_instance = Physical.objects.filter(Patient=patient_instance)
    Standard_instance = Standard.objects.filter(Patient=patient_instance)
    
    patient_session = request.session.get("patient",None)
    if patient_session is not None:
        del request.session['patient']
            
    request.session["patient"] =  patient_instance
    
    
    t=get_template('sle/patient_view_edit.html')
    c=RequestContext(request,locals())
    return HttpResponse(t.render(c))


def sle_login(request):
    form = Login_Form(request.POST or None)
    print '111'
    if form is not None:
        print '222'
        if form.is_valid():
            username = request.POST['username']
            password = request.POST['password']
            print username
            user = authenticate(username=username, password=password)
            if user is not None:
                print '333'
                login(request, user)
                return HttpResponseRedirect("/sle/patient/list/")
        else:
            form = Login_Form()
    t=get_template('sle/login.html')
    c=RequestContext(request,locals())
    return HttpResponse(t.render(c))


def sle_logout(request):
    logout(request)    
    t=get_template('sle/login.html')
    c=RequestContext(request,locals())
    return HttpResponse(t.render(c))

@login_required
def password_change(request): 
    template = {} 
    form = password_change_Form()     
    if request.method=="POST": 
        form = password_change_Form(request.POST.copy()) 
        if form.is_valid(): 
            username = request.user.username 
            oldpassword = form.cleaned_data["oldpassword"] 
            newpassword = form.cleaned_data["newpassword"] 
            newpassword1 = form.cleaned_data["newpassword1"] 
            user = authenticate(username=username,password=oldpassword) 
            if user: #原口令正确 
                if newpassword == newpassword1:#两次新口令一致 
                    user.set_password(newpassword) 
                    user.save() 
                    flag = 1
                    result = simplejson.dumps(flag)
                    return HttpResponse(result)
                else:#两次新口令不一致 
                    template["word"] = '两次输入口令不一致'   
                    template["form"] = form 
                    flag = 0
                    result = simplejson.dumps(flag)
                    return HttpResponse(result)
            else:  #原口令不正确 
                if newpassword == newpassword1:#两次新口令一致 
                    template["word"] = '原口令不正确'   
                    template["form"] = form 
                    flag = 2
                    result = simplejson.dumps(flag)
                    return HttpResponse(result) 
                else:#两次新口令不一致 
                    template["word"] = '原口令不正确，两次输入口令不一致'   
                    template["form"] = form 
                    flag = 3
                    result = simplejson.dumps(flag)
                    return HttpResponse(result)  
        
        
        
@login_required        
def search_patient(request):
    query = request.GET.get('q', '')
    print query
    print '1111'
    if query:
        print '2222'
        if query.isdigit():
            print '3333'
            qset = (
                    Q(patient_name=query) |
                    Q(patient_number=query)
                    )
        else:
            print '4444'
            qset = (
                    Q(patient_name=query)
                    )

        list_items = patient.objects.filter(qset).distinct()
        print '5555'
    else:
        list_items = []
        print '666666'
   
    paginator = Paginator(list_items ,10)
    try:
        page = int(request.GET.get('page', '1'))
    except ValueError:
        page = 1

    try:
        list_items = paginator.page(page)
    except :
        list_items = paginator.page(paginator.num_pages)
        
    print ')))'    

    t = get_template('sle/list_patient.html')
    c = RequestContext(request,locals())
    return HttpResponse(t.render(c))

@login_required
def search_PatientNo(request):
    query = request.GET.get('q', '')
    print query
    if query :
        qset = (
                    Q(Patient_no=query)
                )
        the_patientNo = PatientNo.objects.filter(qset).distinct()[0]
        list_items = patient.objects.filter(id = the_patientNo.patient_id).distinct()
    else:
        list_items = []
    paginator = Paginator(list_items ,10)
    try:
        page = int(request.GET.get('page', '1'))
    except ValueError:
        page = 1
    try:
        list_items = paginator.page(page)
    except :
        list_items = paginator.page(paginator.num_pages)   

    t = get_template('sle/list_patient.html')
    c = RequestContext(request,locals())
    return HttpResponse(t.render(c))

@login_required
def search_hospitalized(request):
    query = request.GET.get('q', '')
    print query
    if query :
        qset = (
                    Q(hospitalized_no=query)
                )
        the_hospitalized = hospitalized.objects.filter(qset).distinct()[0]
        list_items = patient.objects.filter(id = the_hospitalized.patient_id).distinct()
    else:
        list_items = []
    paginator = Paginator(list_items ,10)
    try:
        page = int(request.GET.get('page', '1'))
    except ValueError:
        page = 1
    try:
        list_items = paginator.page(page)
    except :
        list_items = paginator.page(paginator.num_pages)   

    t = get_template('sle/list_patient.html')
    c = RequestContext(request,locals())
    return HttpResponse(t.render(c))

@login_required
def patient_chart(request,id):
    t = get_template('sle/patient_analysis.html')
    c = RequestContext(request,locals())
    return HttpResponse(t.render(c))

@login_required
def patients_chart(request):
    t = get_template('sle/patients_analysis.html')
    c = RequestContext(request,locals())
    return HttpResponse(t.render(c))

@login_required
def ssddi_chart(request):
    patient = request.GET.get('patient_id', '')
    bdate = request.GET.get('bdate', '')
    edate = request.GET.get('edate', '')
    ssddis = []
    
    if patient and bdate and edate:
        follows = Follow.objects.filter(Patient_id = patient,inputdate__gte = bdate,inputdate__lte = edate)
        
        for the_f in follows:
            arrary = []
            
            print the_f.inputdate.strftime('%Y-%m-%d')
            arrary.append(the_f.inputdate.strftime('%Y-%m-%d'))
            arrary.append(the_f.ssddi)
            ssddis.append(arrary)            

        result = simplejson.dumps(ssddis)
        return HttpResponse(result)
        
        
@login_required        
def ssdi_chart(request):
    patient = request.GET.get('patient_id', '')
    bdate = request.GET.get('bdate', '')
    edate = request.GET.get('edate', '')
    ssddis = []
#    ssddis2 = []
#    ssddis3 = []
    
    if patient and bdate and edate:
        follows = Follow.objects.filter(Patient_id = patient,inputdate__gte = bdate,inputdate__lte = edate)
        
        for the_f in follows:
            arrary = []
#            arrary2 = []
            
            print the_f.inputdate.strftime('%Y-%m-%d')
            arrary.append(the_f.inputdate.strftime('%Y-%m-%d'))
            arrary.append(the_f.ssdi)
            ssddis.append(arrary)
#            arrary2.append(the_f.inputdate.strftime('%Y-%m-%d'))
#            arrary2.append(the_f.ssddi+2)
#            ssddis2.append(arrary2)
            
#        ssddis3 = [ssddis,ssddis2]
        result = simplejson.dumps(ssddis)
        return HttpResponse(result)        
        
        
@login_required       
def essdai_chart(request):
    patient = request.GET.get('patient_id', '')
    bdate = request.GET.get('bdate', '')
    edate = request.GET.get('edate', '')
    ssddis = []
    
    if patient and bdate and edate:
        follows = Follow.objects.filter(Patient_id = patient,inputdate__gte = bdate,inputdate__lte = edate)
        
        for the_f in follows:
            arrary = []
            
            print the_f.inputdate.strftime('%Y-%m-%d')
            arrary.append(the_f.inputdate.strftime('%Y-%m-%d'))
            arrary.append(the_f.essdai)
            ssddis.append(arrary)            

        result = simplejson.dumps(ssddis)
        return HttpResponse(result)

@login_required
def esspri_chart(request):
    patient = request.GET.get('patient_id', '')
    bdate = request.GET.get('bdate', '')
    edate = request.GET.get('edate', '')
    ssddis = []
    
    if patient and bdate and edate:
        follows = Follow.objects.filter(Patient_id = patient,inputdate__gte = bdate,inputdate__lte = edate)
        
        for the_f in follows:
            arrary = []
            
            print the_f.inputdate.strftime('%Y-%m-%d')
            arrary.append(the_f.inputdate.strftime('%Y-%m-%d'))
            arrary.append(int(the_f.esspri))
            ssddis.append(arrary)            

        result = simplejson.dumps(ssddis)
        return HttpResponse(result)    
    
@login_required    
def pcs_chart(request):
    patient = request.GET.get('patient_id', '')
    bdate = request.GET.get('bdate', '')
    edate = request.GET.get('edate', '')
    ssddis = []
    
    if patient and bdate and edate:
        follows = Follow.objects.filter(Patient_id = patient,inputdate__gte = bdate,inputdate__lte = edate)
        
        for the_f in follows:
            arrary = []
            
            print the_f.inputdate.strftime('%Y-%m-%d')
            arrary.append(the_f.inputdate.strftime('%Y-%m-%d'))
            arrary.append(the_f.sf12_pcs)
            ssddis.append(arrary)            

        result = simplejson.dumps(ssddis)
        return HttpResponse(result)    
    
@login_required    
def mcs_chart(request):
    patient = request.GET.get('patient_id', '')
    bdate = request.GET.get('bdate', '')
    edate = request.GET.get('edate', '')
    ssddis = []
    
    if patient and bdate and edate:
        follows = Follow.objects.filter(Patient_id = patient,inputdate__gte = bdate,inputdate__lte = edate)
        
        for the_f in follows:
            arrary = []
            
            print the_f.inputdate.strftime('%Y-%m-%d')
            arrary.append(the_f.inputdate.strftime('%Y-%m-%d'))
            arrary.append(the_f.sf12_mcs)
            ssddis.append(arrary)            

        result = simplejson.dumps(ssddis)
        return HttpResponse(result)    


@login_required 
def comprehensive_chart(request):
    bdate = request.GET.get('bdate', '')
    edate = request.GET.get('edate', '')
    index = request.GET.get('index', '')
    sex = request.GET.get('sex', '')
    age = request.GET.get('age', '')
    tsex =''
    
    arg2 = []
    arg3 = []
    
    if index and bdate and edate and sex and age :
        ages = age.split('-')
        if sex =='0':
            
            
            print tsex
            patients = patient.objects.filter(patient_gender = tsex,
                                          patient_age__gte=ages[0],
                                          patient_age__lte=ages[1])
            print patients.count()
            for thep in patients :
                arg1=[]
                thefollows = Follow.objects.filter(Patient = thep
                                                  ,inputdate__gte = bdate,
                                                  inputdate__lte = edate)
                
                for tf in thefollows:
                    arrary = []
                    arrary.append(tf.inputdate.strftime('%Y-%m-%d'))
                    if index == 'ssddi':
                        print index
                        arrary.append(tf.ssddi)
                    elif index == 'ssdi':
                        print index
                        arrary.append(tf.ssdi)
                    elif index == 'essdai':
                        print index
                        arrary.append(tf.essdai)
                    elif index == 'esspri':
                        print index
                        arrary.append(int(tf.esspri))
                    elif index == 'pcs':
                        print index
                        arrary.append(tf.sf12_pcs)                
                    else :
                        print index
                        arrary.append(tf.sf12_mcs)
                    arg1.append(arrary)
                if arg1:    
                    arg2.append(arg1)    
            print arg2            
            
        elif sex == '1':

            
            print tsex
            patients = patient.objects.filter(patient_gender = tsex,
                                          patient_age__gte=ages[0],
                                          patient_age__lte=ages[1])
            print patients.count()
            for thep in patients :
                arg1=[]
                thefollows = Follow.objects.filter(Patient = thep
                                                  ,inputdate__gte = bdate,
                                                  inputdate__lte = edate)
                
                for tf in thefollows:
                    arrary = []
                    arrary.append(tf.inputdate.strftime('%Y-%m-%d'))
                    if index == 'ssddi':
                        print index
                        arrary.append(tf.ssddi)
                    elif index == 'ssdi':
                        print index
                        arrary.append(tf.ssdi)
                    elif index == 'essdai':
                        print index
                        arrary.append(tf.essdai)
                    elif index == 'esspri':
                        print index
                        arrary.append(int( tf.esspri))
                    elif index == 'pcs':
                        print index
                        arrary.append(tf.sf12_pcs)                
                    else :
                        print index
                        arrary.append(tf.sf12_mcs)
                    arg1.append(arrary)
                if arg1:
                    arg2.append(arg1)    
            print arg2            
            
        else:
            
            print tsex
            
            patients = patient.objects.filter(
                                          patient_age__gte=ages[0],
                                          patient_age__lte=ages[1])
            print patients.count()
            for thep in patients :
                arg1=[]
                thefollows = Follow.objects.filter(Patient = thep
                                                  ,inputdate__gte = bdate,
                                                  inputdate__lte = edate)
                
                for tf in thefollows:
                    arrary = []
                    arrary.append(tf.inputdate.strftime('%Y-%m-%d'))
                    if index == 'ssddi':
                        print index
                        arrary.append(tf.ssddi)
                    elif index == 'ssdi':
                        print index
                        arrary.append(tf.ssdi)
                    elif index == 'essdai':
                        print index
                        arrary.append(tf.essdai)
                    elif index == 'esspri':
                        print index
                        arrary.append(int(tf.esspri))
                    elif index == 'pcs':
                        print index
                        arrary.append(tf.sf12_pcs)                
                    else :
                        print index
                        arrary.append(tf.sf12_mcs)
                    arg1.append(arrary)
                if arg1:
                    arg2.append(arg1)    
            print arg2            
        
        result = simplejson.dumps(arg2)
        return HttpResponse(result)
        
    












   